package com.example.cloud.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * HTTP工具类
 */
@Slf4j
public class HttpUtil {

    private static final RestTemplate restTemplate = new RestTemplate();
    private static final int MAX_REDIRECTS = 5;

    /**
     * 获取重定向后的真实URL
     *
     * @param shortUrl 短链接
     * @return 重定向后的真实URL
     */
    public static String getRedirectUrl(String shortUrl) {
        try {
            // 首先从输入文本中提取URL
            String extractedUrl = extractUrl(shortUrl);
            if (extractedUrl != null) {
                shortUrl = extractedUrl;
                log.info("从文本中提取的URL: {}", shortUrl);
            }
            
            // 处理URL中的特殊字符
            shortUrl = cleanUrl(shortUrl);
            log.info("清理后的URL: {}", shortUrl);
            
            // 使用HttpURLConnection手动处理重定向
            return followRedirects(shortUrl, 0);
        } catch (Exception e) {
            log.error("获取重定向URL失败: {}", e.getMessage(), e);
            return shortUrl;
        }
    }
    
    /**
     * 手动处理重定向
     * 
     * @param urlString URL字符串
     * @param redirectCount 重定向计数
     * @return 最终URL
     */
    private static String followRedirects(String urlString, int redirectCount) throws IOException {
        if (redirectCount > MAX_REDIRECTS) {
            log.warn("达到最大重定向次数: {}", urlString);
            return urlString;
        }
        
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        
        int responseCode = connection.getResponseCode();
        log.info("URL: {} 响应码: {}", urlString, responseCode);
        
        if (responseCode >= 300 && responseCode < 400) {
            String location = connection.getHeaderField("Location");
            if (location != null) {
                // 处理相对URL
                if (!location.startsWith("http")) {
                    URL baseUrl = new URL(urlString);
                    location = new URL(baseUrl, location).toString();
                }
                
                log.info("重定向到: {}", location);
                return followRedirects(location, redirectCount + 1);
            }
        }
        
        return urlString;
    }
    
    /**
     * 清理URL，处理特殊字符
     * 
     * @param url 原始URL
     * @return 清理后的URL
     */
    private static String cleanUrl(String url) {
        try {
            // 处理URL中的@符号和其他特殊字符
            if (url.contains("@")) {
                url = url.substring(url.lastIndexOf("@") + 1);
            }
            
            // 解码URL
            url = URLDecoder.decode(url, StandardCharsets.UTF_8.name());
            
            // 移除URL中的空格和其他不合法字符
            url = url.trim().replaceAll("\\s+", "");
            
            return url;
        } catch (Exception e) {
            log.error("清理URL失败: {}", e.getMessage(), e);
            return url;
        }
    }
    
    /**
     * 从文本中提取URL
     *
     * @param text 包含URL的文本
     * @return 提取的URL，如果没有找到则返回null
     */
    private static String extractUrl(String text) {
        // 匹配URL的正则表达式，支持抖音特殊格式
        Pattern pattern = Pattern.compile("(https?://[\\w\\-]+(\\.[\\w\\-]+)+([\\w\\-.,@?^=%&:/~+#]*[\\w\\-@?^=%&/~+#])?)");
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param url 文件URL
     * @return 文件字节数组
     */
    public static byte[] downloadFile(String url) {
        try {
            // 创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            
            // 创建请求实体
            RequestEntity<Void> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI(url));
            
            // 执行请求
            ResponseEntity<byte[]> response = restTemplate.exchange(requestEntity, byte[].class);
            
            // 返回文件内容
            return response.getBody();
        } catch (Exception e) {
            log.error("下载文件失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取文件名
     *
     * @param url 文件URL
     * @return 文件名
     */
    public static String getFileName(String url) {
        try {
            URL fileUrl = new URL(url);
            String path = fileUrl.getPath();
            return path.substring(path.lastIndexOf('/') + 1);
        } catch (Exception e) {
            log.error("获取文件名失败: {}", e.getMessage(), e);
            return "unknown";
        }
    }
} 